package com.nantai.jiafang.nantaijiafang.nt5s.Activity;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.Toast;

import com.nantai.jiafang.nantaijiafang.Data;
import com.nantai.jiafang.nantaijiafang.R;
import com.nantai.jiafang.nantaijiafang.nt5s.Control.MYListView;
import com.nantai.jiafang.nantaijiafang.nt5s.IConstant;
import com.nantai.jiafang.nantaijiafang.nt5s.adapter.ReportDataAdapter;
import com.nantai.jiafang.nantaijiafang.nt5s.utils.Tools;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class ReportActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView tv_back;
    private Button btn_search;
    private Context mContext;
    private TextView tv_start_date;
    private TextView tv_end_date;
    private Calendar calendar;
    private ProgressDialog progressDialog;
    private MYListView listView;
    private ReportDataAdapter reportDataAdapter;
    private int current_start_end_date_state = 1;
    private JSONArray ja;
    private TextView tv_workgroup;
    private String[] strs_group;
    private ArrayList<String> group = new ArrayList<>();
    private JSONArray organization;
    private List<String> list_group;
    private Map<String, String> map;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_report);
        mContext = ReportActivity.this;
        initView();
        setup();
    }
    private void initView() {
        progressDialog = new ProgressDialog(mContext);
        progressDialog.setMessage("正在获取数据，请稍候");
        calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        tv_end_date = (TextView) findViewById(R.id.report_tv_end_date);
        tv_start_date = (TextView) findViewById(R.id.report_tv_start_date);
        btn_search = (Button) findViewById(R.id.report_btn_search);
        tv_back = (TextView) findViewById(R.id.report_tv_back);
        listView = (MYListView) findViewById(R.id.lv_report);
        tv_workgroup = (TextView) findViewById(R.id.tv_group_quality);
        list_group = new ArrayList<>();

        map = new HashMap<>();

    }

    private void setup() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String date = format.format(calendar.getTime());
        tv_end_date.setText(date);
        calendar.add(Calendar.MONTH, -2);
        date = format.format(calendar.getTime());
        tv_start_date.setText(date);
        tv_end_date.setOnClickListener(this);
        tv_start_date.setOnClickListener(this);
        tv_back.setOnClickListener(this);
        btn_search.setOnClickListener(this);
        getQualityOrganization();
//        getQualityStandard();
//        tv_quality.setOnClickListener(this);
        tv_workgroup.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        switch (view.getId()) {
            case R.id.report_tv_back:
                finish();
                break;
            case R.id.report_btn_search:

                if (Tools.isNetAvailuable(mContext)) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    try {
                        Date d1 = sdf.parse(tv_start_date.getText().toString());
                        Date d2 = sdf.parse(tv_end_date.getText().toString());
                        if (d1.after(d2)) {
                            Tools.showToast(mContext, "开始日期要在结束日期之后");
                        } else {
                            progressDialog.show();
                            getDataFromNet();
                        }
                    } catch (ParseException ignored) {

                    }

                } else {
                    Tools.showToast(mContext, "当前网络不可用，请检查网络");
                }

                break;
            case R.id.report_tv_start_date:
                current_start_end_date_state = 1;
                DatePickerDialog dpd = new DatePickerDialog(mContext, Datelistener, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
                dpd.show();
                break;
            case R.id.report_tv_end_date:
                current_start_end_date_state = 2;
                DatePickerDialog dpd2 = new DatePickerDialog(mContext, Datelistener, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
                dpd2.show();
                break;

            case R.id.tv_group_quality:
                showWorkShopDialog();
                break;
        }
    }
    private DatePickerDialog.OnDateSetListener Datelistener = new DatePickerDialog.OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int myyear, int monthOfYear, int dayOfMonth) {
            String monthStr = "",dayStr="";
            if((monthOfYear+1) < 10) {
                monthStr = "0"+(monthOfYear+1);
            }else{
                monthStr = ""+ (monthOfYear+1);
            }

            if(dayOfMonth < 10) {
                dayStr = "0"+dayOfMonth;
            }else{
                dayStr = ""+dayOfMonth;
            }

            if (current_start_end_date_state == 2) {
                tv_end_date.setText(myyear + "-" + monthStr + "-" + dayStr);
            } else {
                tv_start_date.setText(myyear + "-" + monthStr+ "-" + dayStr);
            }
        }
    };

    public static int daysBetween(Date smdate, Date bdate) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        smdate = sdf.parse(sdf.format(smdate));
        bdate = sdf.parse(sdf.format(bdate));
        Calendar cal = Calendar.getInstance();
        cal.setTime(smdate);
        long time1 = cal.getTimeInMillis();
        cal.setTime(bdate);
        long time2 = cal.getTimeInMillis();
        long between_days = (time2 - time1) / (1000 * 3600 * 24);

        return Integer.parseInt(String.valueOf(between_days));
    }

    private void getQualityOrganization() {
        RequestParams params = new RequestParams(IConstant.URL + "getOrganization");
        System.out.println("请求的URL：" + params.toString());
        x.http().post(params, new Callback.CommonCallback<String>() {

            @Override
            public void onSuccess(String result) {
                System.out.println("返回结果：" + result);
                try {
                    organization = new JSONArray(result);
                    for (int i = 0; i < organization.length(); i++) {
                        JSONObject jo = (JSONObject) organization.get(i);
                        list_group.add(jo.optString("DeptName"));
                        map.put(jo.optString("DeptName"), jo.optString("DeptNo"));
                    }
                    strs_group = (String[]) list_group.toArray(new String[0]);
                    System.out.println("部门名称" + strs_group);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }


    private void showWorkShopDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("车间组别");
        group.clear();

        builder.setMultiChoiceItems(strs_group, null, new DialogInterface.OnMultiChoiceClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which, boolean isChecked) {

                if (isChecked) {
                    group.add(strs_group[which]);
                }else
                {
                    group.remove(strs_group[which]);
                }

            }

        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (group.size()==0){
                    tv_workgroup.setText("请选择车间");
                }else {
                    tv_workgroup.setText(append(group).deleteCharAt(append(group).length() - 1).toString());
                }
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        builder.show();
    }
    private StringBuffer append(ArrayList<String> listt){
        StringBuffer str=new StringBuffer(1000);
        for (String s :
                listt) {
            str.append(s+",");
        }
        return str;
    }

    private void getDataFromNet() {
        RequestParams params = new RequestParams(IConstant.URL + "getChart");
        params.addBodyParameter("BeginDate", tv_start_date.getText().toString());
        params.addBodyParameter("OutDate", tv_end_date.getText().toString());
        params.addBodyParameter("UserName", Data.NT5S_Account);
        StringBuffer stringBuffer = new StringBuffer(1000);

        for (int i = 0; i < tv_workgroup.getText().toString().split(",").length; i++) {
            stringBuffer.append(map.get(tv_workgroup.getText().toString().split(",")[i]) + ",");
        }
        stringBuffer.deleteCharAt(stringBuffer.length() - 1);
        params.addBodyParameter("WorkShop", stringBuffer.toString());

//        System.out.println("请求的URL：" + params.toString());
        x.http().post(params, new Callback.CommonCallback<String>() {

            @Override
            public void onSuccess(String result) {
                progressDialog.dismiss();
//                System.out.println("返回结果：" + result);
                try {
                    ja = new JSONArray(result);
                    if (ja != null && ja.length() > 0) {
//                        System.out.println("JSONArray:"+ja);
                        reportDataAdapter = new ReportDataAdapter(mContext, ja);
                        listView.setAdapter(reportDataAdapter);
                    }

                } catch (JSONException e) {
                    System.out.println("解析错误：" + e.toString());
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                progressDialog.dismiss();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                progressDialog.dismiss();
                Toast.makeText(mContext, "cancelled", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFinished() {
                progressDialog.dismiss();
            }
        });

    }
}
